<?php
/**
 * 制作:  叶风
 * Qq:    355007778
 * Email: ye.fn@163.com 
 * 
 */
class zip
{
/**
 * 创建压缩文件
 */
	function create($files, $outFile, $isAdd=0)
	{
		$this->zip = new ZipArchive;
		if (is_file($outFile) && !$isAdd)
			unlink ($outFile);
		if (!$this->zip->open($outFile, ZipArchive::CREATE))
			return false;
		
		is_array($files) or $files = array($files);
		foreach ($files as $f)
		  {
			$f = realpath($f);
		  	$this->baseDir = dirname($f) . DIRECTORY_SEPARATOR;
			
			if (!file_exists($f))
				return false;
			if (is_dir($f))
			 {
				if (strstr(realpath(dirname($outFile)), $f))
					return false;
				if (substr($f, -1)==DIRECTORY_SEPARATOR)
					$f = substr($f, 0, -1);
			 }
			$this->addFile($f);
		  }	
		$this->zip->close(); 
		return true;
	}
	//循环目录下的文件
	function addFile($file)
	{
		$outFile = str_replace($this->baseDir, '', $file);
		if(is_file($file))
		  {
		  	$this->zip->addFile($file, $outFile);
		  	return ;
		  }
		$this->zip->addEmptyDir($outFile);
		
		foreach(glob($file. DIRECTORY_SEPARATOR. '*') as $f)	  	
			$this->addFile($f);
	}
/**
 * 解压
 */
	function extract($file, $dir='')
	{
		$dir or $dir =dirname($file);
		$a = pathinfo($file);
		$ext = strtolower($a['extension']);
		if ($ext=='rar')
		 {
			$r = RarArchive::open($file);
			if (!$r)
				return;
			foreach($r->getEntries() as $f)
				$f->extract($dir);
			$r->close();
		 }
		else{
			$r = new ZipArchive;
			if( !$r->open($file))
				return; 
			$r->extractTo($dir);
			$r->close();
		 }
		return true;
	}
}

?>